package com.skywork.controller.exception;

import java.util.Map;

import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.skywork.controller.response.base.BaseResponse;
import com.skywork.utils.ValidatorUtils;

/**
 * 自定义ExceptionHandler，专门处理Restful异常.
 * 
 * @author junchao
 */
// 会被Spring-MVC自动扫描，但又不属于Controller的annotation。
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

	@Autowired
	private ObjectMapper objectMapper;
	/**
	 * 处理RestException.
	 */
	@ExceptionHandler(value = { RestException.class })
	public final ResponseEntity<?> handleException(RestException ex, WebRequest request) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(MimeTypeUtils.APPLICATION_JSON_VALUE));
		String response = null;
		try {
			response = objectMapper.writeValueAsString(new BaseResponse<Object>(ex.status.toString(), ex.getMessage().toString()));
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return handleExceptionInternal(ex, response, headers, ex.status, request);
	}

	/**
	 * 处理JSR311 Validation异常.
	 */
	@ExceptionHandler(value = { ConstraintViolationException.class })
	public final ResponseEntity<?> handleException(ConstraintViolationException ex, WebRequest request) {
		Map<String, String> errors = ValidatorUtils.extractPropertyAndMessage(ex.getConstraintViolations());

		String response = null;
		try {
			response = objectMapper.writeValueAsString(new BaseResponse<Object>("-1", errors.toString()));

		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(MimeTypeUtils.APPLICATION_JSON_VALUE));
		return handleExceptionInternal(ex, response, headers, HttpStatus.BAD_REQUEST, request);
	}
}
